package com.zzy.netty.learn.server;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

import com.zzy.netty.learn.common.Request;
import com.zzy.netty.learn.common.Response;
import com.zzy.netty.learn.common.util.SerializeUtil;
/**
 * 消息接受处理类
 * @author -琴兽-
 *
 */
public class NettyServerMsgHandler extends SimpleChannelHandler {
	
	
	public static Map<String,Channel> channelMap=new ConcurrentHashMap<String,Channel>();

	/**
	 * 接收消息
	 */
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		 String requestStr = (String) e.getMessage();
		 Request request = SerializeUtil.unFastJsonSerialize(requestStr, Request.class);
		 channelMap.put(request.getPlayerId(), ctx.getChannel());
		 
		 System.out.println("Server: messageReceived---------"+requestStr);
		 
		 //这里处理业务  耗时操作 需要  重新    开启线程池 !!!!!  或者队列
		 
		 
		 //需要异步回写数据!!!!
		 Response response = new Response(request);
		 reply(response);
		 
		 super.messageReceived(ctx, e);
	}
	

	public static void reply(Response response) {
		 String msg = "你好"+response.getPlayerId();
		 response.setData(msg.getBytes());
		 Channel channel = channelMap.get(response.getPlayerId());
		 String responseStr = SerializeUtil.fastJsonSerialize(response);
		 channel.write(responseStr);
	}
	
	
	
	
	
	
	
	
	
	

	/**
	 * 捕获异常
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
		System.out.println("Server: exceptionCaught");
		super.exceptionCaught(ctx, e);
	}

	/**
	 * 新连接
	 */
	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		System.out.println("Server: channelConnected");
		super.channelConnected(ctx, e);
	}

	/**
	 * 必须是链接已经建立，关闭通道的时候才会触发
	 */
	@Override
	public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		System.out.println("Server: channelDisconnected");
		super.channelDisconnected(ctx, e);
	}

	/**
	 * channel关闭的时候触发
	 */
	@Override
	public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		System.out.println("Server: channelClosed");
		super.channelClosed(ctx, e);
	}
}
